package org.davidliebman.android.flyer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import org.davidliebman.android.flyer.InitBackground.LevelList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class InitFlyerChallenges {
	
	GameValues mGameV;
	Context mContext;
	ParseChallengeXML mParser;
	LevelList mLevelList;
	boolean mLookForXml;

	public InitFlyerChallenges(GameValues gV, Context context, boolean mLookForXml) {
		mGameV = gV;
		mContext = context;
		mParser = new ParseChallengeXML(mContext);
		this.mLookForXml = mLookForXml;
		this.populateLevelList();

	}
	/* set level challenge info */
	public void setLevel(int num) {
		boolean test = false;
		int mSearchNum = num;
		//int mFindNum = 0;
		
		try {
			test = mParser.setXmlPullParser(mGameV.isLookForXml());
			if (test ) test = mParser.parseChallengeXml(mSearchNum, mGameV);
		}
		catch (Exception e) {
			//Log.e("INIT LEVEL",e.getMessage());
			
		}
		//try again without sdcard.
		if (test == false ) {
			try {
				mParser.setXmlPullParser(false);
				mParser.parseChallengeXml(mSearchNum, mGameV);
			}
			catch (Exception e) {
				//Log.e("INIT LEVEL",e.getMessage());
				
			}
			
		}

	}
	public void populateLevelList() {
		mLevelList = this.mParser.getLevelList(mLookForXml);
		mGameV.setLevelList(mLevelList);
	}
}

class ParseChallengeXML {
	private Context mContext;
	private GameValues mGameV;
	private XmlPullParser mXpp;
	private int mFoundBackgroundNum;
	
	public static final String SDCARD_FILE = new String ("flyerchallenge.xml");

	
	final String NUMBER = new String("number");
	final String VERTICAL = new String("vertical");
	final String HORIZONTAL = new String("horizontal");
	final String LEVEL = new String("level");
	final String USE_BG = new String("use_bg");
	final String CHALLENGE = new String("challenge");
	
	final String TILES = new String("tiles_level");
	final String OBJECTS = new String("tiles_objects");
	
	final String LAST = new String("last_level");
	final String GAME = new String("game");
	
	public ParseChallengeXML(Context context) {
		mContext = context;
		//this.mGameV = new GameValues();
	}
	
	public boolean setXmlPullParser(boolean mLookForXml) throws XmlPullParserException, IOException{
		if (!mLookForXml) {
			mXpp = mContext.getResources().getXml(R.xml.flyerchallenge);
		}
		else {
			
		   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		   factory.setNamespaceAware(true);
		   mXpp = factory.newPullParser(); 	
		   File sdcard = Environment.getExternalStorageDirectory();
		   //Log.e("XML", sdcard.getAbsolutePath());
		   int BUFFER_SIZE = 8192;

		   
		   File mFileInput = new File(sdcard, SDCARD_FILE);
		   
		   FileReader mReader = new FileReader(mFileInput);
		   
		   BufferedReader in = new BufferedReader(mReader,BUFFER_SIZE);

		   mXpp.setInput(in);
			   
		}
		return true;
	}
	

	
	public boolean parseChallengeXml(int num, GameValues mGameV) throws XmlPullParserException, IOException {
		boolean mStopParse = false;
		boolean mReadNum = false;
		int mIndexNum = 0;
		boolean  mBG, mChallenge;

		String mCList = new String();
		mGameV.initChallengeList();

		mBG = false;
		mChallenge = false;


		int mUseBg = 0;


		int eventType = mXpp.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT && !mStopParse) {

			//System.out.println("name: " + mXpp.getName());

			if(eventType == XmlPullParser.START_TAG && mXpp.getName().equalsIgnoreCase(LEVEL) ) {

				/* get 'number' attribute from xml tag 'level' */
				if (mXpp.getAttributeCount() == 1 && mXpp.getAttributeName(0).contentEquals( NUMBER)) {

					mIndexNum = new Integer(mXpp.getAttributeValue(0).toString().trim()).intValue();
					if (mIndexNum == num) mStopParse = true;
				}
				else {
					//Log.e("XML", mXpp.getAttributeName(0) + " " + mXpp.getAttributeCount());
				}


			}
			eventType = mXpp.next();
			//}

			//eventType = mXpp.next();

			if(  mIndexNum == num) {
				/* found right level entry !!*/
				while (!(eventType == XmlPullParser.END_TAG && mXpp.getName().contentEquals(USE_BG))) {

					//mUseBg
					if(eventType == XmlPullParser.START_TAG && mXpp.getName().contentEquals(USE_BG)) {
						mBG = true;
					} else if(eventType == XmlPullParser.END_TAG && mXpp.getName().contentEquals(USE_BG)) {
						mBG = false;
					} else if(eventType == XmlPullParser.TEXT && mBG == true) {
						mUseBg = new Integer(mXpp.getText()).intValue();
						this.mFoundBackgroundNum = mUseBg;

					}
					eventType = mXpp.next();
				}


				while(!(eventType == XmlPullParser.END_TAG && mXpp.getName().contentEquals(LEVEL))) {
					//mChallenge
					if(eventType == XmlPullParser.START_TAG && mXpp.getName().contentEquals(CHALLENGE)) {
						mChallenge = true;
					} else if(eventType == XmlPullParser.END_TAG && mXpp.getName().contentEquals(CHALLENGE)) {
						mChallenge = false;
					} else if(eventType == XmlPullParser.TEXT && mChallenge == true) {
						mCList = mXpp.getText();

						//eventType = mXpp.next();

						StringTokenizer mChallengeToken = new StringTokenizer(mCList,",");
						int mTotalChallengeTokens = mChallengeToken.countTokens();
						Challenge temp = new Challenge();

						for (int i = 0; i < mTotalChallengeTokens; i ++ ) {
							int mC = new Integer(mChallengeToken.nextToken().trim()).intValue();
							switch(i) {
							case 0:
								temp.setRings(mC);
								break;
							case 1:
								temp.setBubble1(mC);
								break;
							case 2:
								temp.setBubble2(mC);
								break;
							case 3:
								temp.setBubble3(mC);
								break;
							case 4:
								temp.setInvader1(mC);
								break;
							case 5:
								temp.setInvader2(mC);
								break;
							case 6:
								temp.setInvader3(mC);
								break;
							case 7:
								temp.setSpeed(mC);
								break;
							}
						}
						mGameV.addChallenge(temp);

					}
					eventType = mXpp.next();

				}


				eventType = mXpp.next();

				//}
			}

		}
		return true;
	}
	
	public  InitBackground.LevelList getLevelList(boolean mLookForXml) {
    	boolean test = true;
    	InitBackground.LevelList mList = new InitBackground.LevelList();
    	try {
			test = setXmlPullParser(mLookForXml);
        	mList = getXmlList(null);
		}
		
		catch (XmlPullParserException e) {
			//Log.e("INIT LEVEL","XmlPullParserException -- " + e.getMessage());
		}
		catch (IOException e) {
			//Log.e("INIT LEVEL","IO exception " + e.getMessage());
		}
		catch (Exception e) {
			//Log.e("INIT LEVEL", "exception " + e.getMessage());
		}
		
		//try again without sdcard.
		if (mList.size() == 0 ) {
			try {
				//Log.e("INIT LEVEL","failed mLookForXml -- " + test);

				setXmlPullParser(false);
	        	mList = getXmlList(null);
			}
			catch (Exception e) {
				//Log.e("INIT LEVEL",e.getMessage());
				
			}
			
		}
		return mList;
	}
	
	public LevelList getXmlList(GameValues mGameV) throws XmlPullParserException, IOException{

		LevelList mList = new LevelList();

		int mIndexNum = 0;

		
		int eventType = mXpp.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT ) {
			
			//System.out.println("name: " + mXpp.getName());
			
			if(eventType == XmlPullParser.START_TAG && mXpp.getName().equalsIgnoreCase(LEVEL) ) {
			
				/* get 'number' attribute from xml tag 'level' */
				if (mXpp.getAttributeCount() == 1 && mXpp.getAttributeName(0).contentEquals( NUMBER)) {
					
					mIndexNum = new Integer(mXpp.getAttributeValue(0).toString().trim()).intValue();

					//Log.e("XML", " attribute number " + mIndexNum);
					if(mIndexNum - 1 == mList.size()) {
						mList.add(new String("Room Num "+mIndexNum),mIndexNum);
					}
					else {
						mList.add(new String("Room Num "+ ( mList.size() + 1 )+" ID:"+mIndexNum),mIndexNum);
					}
					//mList.add(mIndexNum);
				}
				else {
					//Log.e("XML", mXpp.getAttributeName(0) + " " + mXpp.getAttributeCount());
				}
			
				
			}
			eventType = mXpp.next();
		}
		if (mGameV != null) {
			mGameV.setTotNumRooms(mList.size());
		}
		return mList;
	}

	public int getFoundBackgroundNum() {
		return mFoundBackgroundNum;
	}

	public void setFoundBackgroundNum(int mFoundBackgroundNum) {
		this.mFoundBackgroundNum = mFoundBackgroundNum;
	}
	
	
}